﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Diagnostics;

namespace PhotoAlbum.Web
{
	/// <summary>
	/// Summary description for View
	/// </summary>
	public class View : IHttpHandler
	{
        private static readonly string NoImagePath = "images/no-image.jpg";
        private static readonly string NoThumbnailPath = "images/no-thumb.jpg";
        private enum Size
        {
            Original,
            Thumbnail
        }

		public void ProcessRequest(HttpContext context)
		{
            var pictureIdString = context.Request.QueryString["id"];
            var pictureId = 0;

            var sizeString = context.Request.QueryString["size"];
            var size = Size.Original;
            if (sizeString != null && sizeString.Equals("thumb", StringComparison.CurrentCultureIgnoreCase))
            {
                size = Size.Thumbnail;
            }

            if (String.IsNullOrEmpty(pictureIdString)
                || !int.TryParse(pictureIdString, out pictureId))
            {
                Fail(context, size);
                return;
            }

            using (var model = new PhotoAlbumModelContainer())
            {
                var image = model.Pictures.FirstOrDefault(i => i.Id == pictureId);

                if (image != null)
                {
                    switch (size)
                    {
                        case Size.Original:
                            context.Response.Redirect(image.Image ?? NoImagePath);
                            break;
                        case Size.Thumbnail:
                            context.Response.Redirect(image.Thumbnail ?? NoThumbnailPath);
                            break;
                    }
                }
                else
                {
                    Fail(context, size);
                }
            }
		}

        private static void Fail(HttpContext context, Size size)
        {
            try
            {
                var relativeImagePath = size == Size.Original ? NoImagePath : NoThumbnailPath;
                context.Response.Redirect(relativeImagePath);
            }
            catch
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Image cannot be retrieved.");
            }
        }

		public bool IsReusable
		{
			get
			{
				return true;
			}
		}
	}
}